//
//  CertificationFirstPageViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/9.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MobileCoreServices
import TZImagePickerController
class CertificationFirstPageViewController: UIViewController {

    

    @IBOutlet weak var idBottomView: UIView!
    
    @IBOutlet weak var idImageView: UIImageView!
    
    @IBOutlet weak var heaaderButton: UIButton!
    fileprivate var scanImage:UIImage?
    fileprivate var headerImage:UIImage?
    fileprivate var inforationArray:NSMutableArray?
    override func viewDidLoad() {
        super.viewDidLoad()
        AipOcrService.shard().auth(withAK: BaiduYunAPIKey, andSK: BaiduYunSecretKey)
        self.heaaderButton.layer.cornerRadius = 52
        self.heaaderButton.layer.masksToBounds = true
        self.idImageView.layer.cornerRadius = 5
        self.idImageView.layer.masksToBounds = true
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(idCardButtonClick(_:)))
        self.idBottomView.addGestureRecognizer(tap)
    }
    
    
    @IBAction func headerButtonClick(_ sender: Any) {
        var responder = self.next
        while !(responder is UIViewController) {
            responder = responder?.next
        }
        if responder is UIViewController {
            let vc = responder as! UIViewController
            
            let tool = PhotoSheet()
            tool.showCTOnlyPhotoSheet(viewController: vc) { [unowned self](images) in
                if images != nil && images!.count > 0 {
                  self.headerImage = images![0]
                  self.heaaderButton.setImage(images![0], for: UIControlState.normal)
                }
            }
            
        }
    }
    @objc func idCardButtonClick(_ sender: UITapGestureRecognizer) {
        let ocrVc = AipCaptureCardVC.viewController(with: .localIdCardFont) { (ocrImage) in
            AipOcrService.shard().detectIdCardFront(from: ocrImage, withOptions: nil, successHandler: { (result) in
                
                DispatchQueue.main.async {
                    self.setupResultWithUI(result as! [String : AnyObject])
                    self.idImageView.image = ocrImage
                    self.scanImage = ocrImage
                    self.dismiss(animated: true, completion: {
                        guard (self.scanImage != nil) else {
                            QWTextonlyHud("身份信息未获取成功", target: self.view)
                            
                            return
                        }
                        let second = CTSecondPageViewController(nibName: "CTSecondPageViewController", bundle: nil)
                        second.informationArray = self.inforationArray
                        
                        second.scanIdImage = self.scanImage
                        second.headerImage = self.headerImage
                    self.navigationController?.pushViewController(second, animated: true)
                    })
                }
            }, failHandler: { (error) in
                
            })
        }
        
        self.present(ocrVc!, animated: true) {
            
        }
        
}
    fileprivate func setupResultWithUI(_ result:[String:AnyObject]){
        self.inforationArray = NSMutableArray.init()
        if (result["words_result"] != nil){
            (result["words_result"])?.enumerateKeysAndObjects({ (mykey, myObj, myStop) in
                guard let selectObj : NSDictionary = myObj as? NSDictionary else{
                    return
                }
                if let selectWord = selectObj["words"] {
                    self.inforationArray?.add(selectWord)
                }else{
                    return
                }
            })
        }else{
            
        }
        
        let userAge = self.switchDateToAge(self.inforationArray![1] as! String)
        self.inforationArray?.replaceObject(at: 1, with: userAge)
    }
    fileprivate func switchDateToAge(_ year:String) -> String{
        
        let formate = DateFormatter()
        formate.dateFormat = "yyyyMMdd"
        let date = formate.date(from: year)
        let currentDate = NSDate()
        let time = currentDate.timeIntervalSince(date!)
        let age = Int(time)/(3600*24*365)
        return String(age)
        
    }
}
/*
extension CertificationFirstPageViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let photo = info[UIImagePickerControllerOriginalImage]
        if photo != nil {
//            if let handler = self.choosePhotoHandler {
//                handler([photo as! UIImage])
//            }
        }
        
        self.dismiss(animated: true) {
            
           // self.removeFromParentViewController()
           // self.view.removeFromSuperview()
            
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true) {
           // self.removeFromParentViewController()
         //   self.view.removeFromSuperview()
        }
    }
}
*/
